<template>
    <view class="container">
        <!-- 房间信息 -->
        <view class="room-info">
            <view class="room-image-wrapper">
                <image :src="roomData.image_url || 'https://ai-public.mastergo.com/ai/img_res/dbef5d324519a8ea1d7dd7b355c94871.jpg'"
                    class="room-image" />
            </view>
            <view class="room-details">
                <view class="room-title">{{ roomData.name || '加载中...' }}</view>
                <view class="room-tags" v-if="roomData.tags && roomData.tags.length">
                    <text class="tag" v-for="(tag, tagIndex) in roomData.tags" :key="tagIndex">{{ tag }}</text>
                </view>
                <view class="room-notice">
                    <text class="notice-label">温馨提示:</text>
                    <view class="notice-content">
                        <text>凌晨1点至9点未保洁的包间</text>
                        <text class="notice-highlight">待保洁状态</text>
                        <text>谨慎下单哦。</text>
                    </view>
                    <text class="notice-warning">下单前请务必确认预约时间</text>
                </view>
            </view>
        </view>

        <!-- 日期选择 -->
        <view class="date-picker">
            <scroll-view scroll-x class="date-scroll">
                <view v-for="(date, index) in dateOptions" :key="index"
                    :class="['date-item', selectedDateIndex === index ? 'active' : '']" @click="selectDate(index)">
                    <text class="date-day">{{ date.day }}</text>
                    <text class="date-label">{{ date.label }}</text>
                </view>
            </scroll-view>
        </view>

        <!-- 时长选择 -->
        <view class="duration-section">
            <text class="section-label">时长选择:</text>
            <view class="duration-options">
                <view class="duration-row">
                    <view v-for="(duration, index) in durationRow1" :key="index"
                        :class="['duration-item', getSelectedDurationClass(duration)]"
                        @click="selectDurationByValue(duration.value)">
                        <text class="duration-value">{{ duration.value }}/小时</text>
                        <text class="duration-price">¥ {{ duration.price }}</text>
                    </view>
                </view>
                <view class="duration-row">
                    <view v-for="(duration, index) in durationRow2" :key="index"
                        :class="['duration-item', getSelectedDurationClass(duration)]"
                        @click="selectDurationByValue(duration.value)">
                        <text class="duration-value">{{ duration.value }}/小时</text>
                        <text class="duration-price">¥ {{ duration.price }}</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 时间选择 -->
        <view class="time-section">
            <text class="section-label">时间选择:</text>
            <view class="time-picker">
                <view class="time-input active" @click="showStartTimePicker">
                    <text>{{ startTime }}</text>
                    <text class="down-arrow">▼</text>
                </view>
                <text class="time-separator">到</text>
                <view class="time-input">
                    <text>{{ endTime }}</text>
                </view>
            </view>

            <!-- 时间选择器弹窗 -->
            <view v-if="showTimePicker" class="picker-mask" @click.stop="cancelTimePicker">
                <view class="time-picker-popup" @click.stop>
                    <view class="picker-header">
                        <text class="cancel-btn" @click="cancelTimePicker">取消</text>
                        <text class="confirm-btn" @click="confirmTimePicker">确定</text>
                    </view>
                    <picker-view class="time-picker-view" :value="pickerValue" @change="onTimePickerChange">
                        <picker-view-column>
                            <view class="picker-item" v-for="hour in hoursList" :key="hour">{{ hour }}时</view>
                        </picker-view-column>
                        <picker-view-column>
                            <view class="picker-item" v-for="minute in minutesList" :key="minute">{{ minute }}分</view>
                        </picker-view-column>
                    </picker-view>
                </view>
            </view>

            <!-- 时间段图例 -->
            <view class="time-legend">
                <view class="legend-item">
                    <view class="legend-color current"></view>
                    <text class="legend-text">当前选择时段</text>
                </view>
                <view class="legend-item">
                    <view class="legend-color available"></view>
                    <text class="legend-text">可选时段</text>
                </view>
                <view class="legend-item">
                    <view class="legend-color unavailable"></view>
                    <text class="legend-text">不可选择时段</text>
                </view>
            </view>

           <!-- 日期时间线 -->
           <view class="timeline">
                <view class="timeline-date">{{ formattedDate }}</view>
                <view class="timeline-hours">
                    <view v-for="hour in 25" :key="hour - 1" :class="['hour-block', getHourClass(hour - 1)]"></view>
                </view>
                <view class="hour-labels">
                    <text v-for="i in 13" :key="i * 2" class="hour-label">{{ (i * 2 - 2) }}</text>
                </view>
            </view>

            <!-- 次日时间线 -->
            <view class="timeline" v-if="showNextDay">
                <view class="timeline-date">{{ formattedNextDate }}</view>
                <view class="timeline-hours">
                    <view v-for="hour in 25" :key="hour - 1" :class="['hour-block', getNextDayHourClass(hour - 1)]"></view>
                </view>
                <view class="hour-labels">
                    <text v-for="i in 13" :key="i * 2" class="hour-label">{{ (i * 2 - 2) }}</text>
                </view>
            </view>
        </view>

        <!-- 订单信息 -->
        <view class="order-info">
            <view class="info-row">
                <text class="info-label">预约时长:</text>
                <text class="info-value">{{ selectedDurationValue }}小时</text>
            </view>
            <view class="info-row">
                <text class="info-label">选择优惠券:</text>
                <text class="info-value">{{ userCoupons.length ? '有可用优惠券' : '无可用优惠券' }}</text>
            </view>
            <view class="info-row">
                <text class="info-label">使用余额:</text>
                <view class="balance-section">
                    <text class="balance-value">{{ formatBalance }}元</text>
                    <view class="recharge-btn" @click="goToRecharge">充值</view>
                </view>
            </view>
        </view>

        <!-- 底部支付栏 -->
        <view class="bottom-bar">
            <view class="price-section">
                <text class="price-label">需支付:</text>
                <text class="price-value">¥ {{ totalPrice }}</text>
            </view>
            <view class="action-btns">
                <!-- <view class="voucher-btn" @click="useVoucher">验券下单</view> -->
                <view class="pay-btn" @click="confirmPayment">验券下单</view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, reactive } from 'vue';
import request from '@/utils/request';

// 类型声明
declare const uni: any;

// 房间数据接口定义
interface IRoom {
    id: string | number;
    name: string;
    image_url: string;
    tags: string[];
    hourly_price: number;
    package_hours?: number;
    package_price?: number;
    status?: string;
    description?: string;
}

// 时长选项接口
interface IDuration {
    value: string;
    price: string;
}

// 日期选项接口
interface IDateOption {
    day: string;
    label: string;
    date: Date;
}

// 页面参数
const roomId = ref<string | number>('');
const roomData = ref<IRoom>({
    id: '',
    name: '',
    image_url: '',
    tags: [],
    hourly_price: 0
});

            // 日期选择
const today = new Date();
const dateOptions = ref<IDateOption[]>([]);
const selectedDateIndex = ref(0);

// 初始化日期选项
const initDateOptions = () => {
    const options: IDateOption[] = [];
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    
    for (let i = 0; i < 5; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        
        const day = `${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getDate().toString().padStart(2, '0')}`;
        const label = i === 0 ? '今天' : weekdays[date.getDay()];
        
        options.push({ day, label, date });
    }
    
    dateOptions.value = options;
};

// 时长选择
const allDurations = ref<IDuration[]>([]);
const selectedDurationValue = ref('2');

// 计算属性：第一行时长选项
const durationRow1 = computed(() => {
    return allDurations.value.slice(0, 3);
});

// 计算属性：第二行时长选项
const durationRow2 = computed(() => {
    return allDurations.value.slice(3);
});

// 计算属性：当前选中的时长对象
const selectedDurationObj = computed(() => {
    return allDurations.value.find(d => d.value === selectedDurationValue.value);
});
const couponDeduction = computed(() => {
    const selectedDuration = parseInt(selectedDurationValue.value);
    const couponHours = parseInt(couponDuration) || 0;
    const applicableHours = Math.min(selectedDuration, couponHours);
    const hourlyPrice = roomData.value.hourly_price;
    return (applicableHours * hourlyPrice).toFixed(2);
});
// 计算属性：当前总价
// 修改计算属性：当前总价
const totalPrice = computed(() => {
    const duration = allDurations.value.find(d => d.value === selectedDurationValue.value);
    const originalPrice = duration ? parseFloat(duration.price) : 0;
    const selectedDuration = parseInt(selectedDurationValue.value);
    const couponHours = parseInt(couponDuration) || 0;

    if (selectedDuration <= couponHours) {
        return '0.00';
    }
    const deduction = parseFloat(couponDeduction.value);
    if(originalPrice - deduction<=0){
        return '0.00';
    }
    return (originalPrice - deduction).toFixed(2);
});

//优惠券抵用时长
const couponDuration = uni.getStorageSync('coupon_duration');
            // 时间选择
const startTime = ref('');
const endTime = ref('');
const showNextDay = ref(false);

            // 时间选择器
const showTimePicker = ref(false);
const pickerValue = ref([0, 0]);
const hoursList = ref<string[]>([]);
const minutesList = ref<string[]>([]);
const tempTime = ref('');

// 初始化时间选择器数据
const initTimePickerData = () => {
    const now = new Date();
    const selectedDate = dateOptions.value[selectedDateIndex.value]?.date;
    const isToday = selectedDate && selectedDate.toDateString() === now.toDateString();

    if (isToday) {
        const currentHour = now.getHours();
        hoursList.value = Array.from({ length: 24 - currentHour }, (_, i) => (currentHour + i).toString().padStart(2, '0'));
        const currentMinute = now.getMinutes();
        if (hoursList.value[0] === now.getHours().toString().padStart(2, '0')) {
            minutesList.value = Array.from({ length: 60 - currentMinute }, (_, i) => (currentMinute + i).toString().padStart(2, '0'));
        } else {
            minutesList.value = Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0'));
        }
    } else {
        hoursList.value = Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0'));
        minutesList.value = Array.from({ length: 60 }, (_, i) => i.toString().padStart(2, '0'));
    }
};

// 格式化日期
const formattedDate = computed(() => {
    const date = dateOptions.value[selectedDateIndex.value]?.date;
    if (!date) return '';
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
});

// 格式化次日日期
const formattedNextDate = computed(() => {
    const date = dateOptions.value[selectedDateIndex.value]?.date;
    if (!date) return '';
    const nextDate = new Date(date);
    nextDate.setDate(date.getDate() + 1);
    return `${nextDate.getFullYear()}-${(nextDate.getMonth() + 1).toString().padStart(2, '0')}-${nextDate.getDate().toString().padStart(2, '0')}`;
});

// 用户数据
const userCoupons = ref<any[]>([]);
const userBalance = ref(0);
const reverseTime = ref<any[]>([]);
// 格式化余额的计算属性
const formatBalance = computed(() => {
    return typeof userBalance.value === 'number' ? userBalance.value.toFixed(2) : '0.00';
});

// 获取房间详情
const fetchRoomDetail = async () => {
    try {
        console.log(`开始获取房间详情，原始ID值: ${roomId.value}，类型: ${typeof roomId.value}`);
        
        // 确保roomId是有效值
        if (!roomId.value) {
            throw new Error('房间ID为空');
        }
        
        // 处理可能的字符串ID，确保是数字格式
        const id = Number(roomId.value);
        if (isNaN(id)) {
            console.warn(`房间ID不是有效数字: ${roomId.value}，将使用原始值请求`);
        } else {
            console.log(`转换后的房间ID: ${id}`);
        }
        
        uni.showLoading({
            title: '加载中'
        });
        
        console.log(`发送API请求: /api/mobile/room/detail/${roomId.value}`);
        const res = await request.get(`/api/mobile/room/detail/${roomId.value}`);
        console.log('房间详情API响应:', res);
        
        if (res.code === 200) {
            // 处理不同的返回结构 - 房间API返回 {room: {...}} 格式
            let roomDataTmp = null;
            if (res.data && res.data.room) {
                console.log('使用res.data.room结构');
                roomDataTmp = res.data.room;
            } else if (res.data) {
                console.log('直接使用res.data结构');
                roomDataTmp = res.data;
            } else {
                console.error('未找到有效的房间数据结构');
                throw new Error('数据结构异常');
            }
            
            console.log('原始房间数据:', roomDataTmp);
            
            // 进行数据规范化处理
            roomData.value = {
                id: roomDataTmp.id || '',
                name: roomDataTmp.name || '未命名房间',
                image_url: roomDataTmp.image_url || '',
                // 后端已将tags转换为字符串数组
                tags: Array.isArray(roomDataTmp.tags) ? roomDataTmp.tags : [],
                // 确保价格是数字
                hourly_price: typeof roomDataTmp.hourly_price === 'number' ? 
                    roomDataTmp.hourly_price : parseFloat(roomDataTmp.hourly_price || '0'),
                package_hours: roomDataTmp.package_hours ? Number(roomDataTmp.package_hours) : undefined,
                package_price: roomDataTmp.package_price ? Number(roomDataTmp.package_price) : undefined,
                status: roomDataTmp.status || '',
                description: roomDataTmp.description || ''
            };
            
            console.log('处理后的房间数据:', roomData.value);
            
            // 验证必要字段是否存在
            if (!roomData.value.name || isNaN(roomData.value.hourly_price)) {
                console.error('房间数据缺少必要字段或格式不正确');
                throw new Error('房间数据无效');
            }
            const response = await request.get(`/api/mobile/reservation/reverseTime/${roomId.value}`);
            console.log('reverseTime API响应:', response.data);
            if(response.code === 200){
                reverseTime.value = response.data;
            }
            console.log('reverseTime已预约时间', reverseTime.value);
            // 根据房间小时价格和套餐价格生成时长选项
            generateDurationOptions();
        } else {
            console.error('获取房间详情失败，状态码:', res.code, '消息:', res.message || '未知错误');
            uni.showToast({
                title: res.message || '获取房间信息失败',
                icon: 'none'
            });
            
            // 如果获取失败，3秒后返回上一页
            setTimeout(() => {
            uni.navigateBack();
            }, 3000);
        }
    } catch (error) {
        console.error('获取房间详情异常:', error);
        uni.showToast({
            title: error.message || '网络异常，请稍后重试',
            icon: 'none'
        });
        
        // 如果异常，3秒后返回上一页
        setTimeout(() => {
            uni.navigateBack();
        }, 3000);
    } finally {
        uni.hideLoading();
    }
};

// 获取用户信息
const fetchUserInfo = async () => {
    try {
        // 使用正确的API路径，根据后端定义
        const res = await request.get('/api/mobile/user/profile');
        
        if (res.code === 200) {
            // 确保balance是数字类型
            if (res.data && res.data.balance !== undefined) {
                userBalance.value = typeof res.data.balance === 'number' ? 
                    res.data.balance : parseFloat(res.data.balance) || 0;
            } else {
                userBalance.value = 0;
            }
            
            // 设置优惠券
            userCoupons.value = Array.isArray(res.data.coupons) ? res.data.coupons : [];
            
            console.log('用户信息获取成功，余额:', userBalance.value, '类型:', typeof userBalance.value);
        } else {
            console.log('获取用户信息返回非200状态:', res);
            // 设置默认值
            userBalance.value = 0;
            userCoupons.value = [];
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
        // 发生错误时设置默认值
        userBalance.value = 0;
        userCoupons.value = [];
    }
};

// 根据房间价格生成时长选项
const generateDurationOptions = () => {
    const options: IDuration[] = [];
    const hourlyPrice = roomData.value.hourly_price || 0;
    
    // 1-6小时的选项
    for (let i = 1; i <= 6; i++) {
        // 如果有套餐价格且小时数匹配，则使用套餐价格
        if (roomData.value.package_hours === i && roomData.value.package_price !== undefined) {
            // 确保package_price是数字类型
            const packagePrice = typeof roomData.value.package_price === 'number' 
                ? roomData.value.package_price 
                : parseFloat(roomData.value.package_price as any);
            
            options.push({
                value: i.toString(),
                price: isNaN(packagePrice) ? '0.00' : packagePrice.toFixed(2)
            });
        } else {
            // 否则使用小时价格 * 小时数，可以添加一些折扣逻辑
            let price = hourlyPrice * i;
            if (i > 1) {
                // 超过1小时有折扣
                price = price * (1 - (i - 1) * 0.05);
            }
            options.push({
                value: i.toString(),
                price: price.toFixed(2)
            });
        }
    }
    
    allDurations.value = options;
};

// 选择日期
const selectDate = (index: number) => {
    selectedDateIndex.value = index;
    initTimePickerData(); // 重新初始化时间选择器数据
};

        // 根据值选择时长
const selectDurationByValue = (value: string) => {
    selectedDurationValue.value = value;
    updateEndTime();
};

        // 获取时长项的选中样式类
const getSelectedDurationClass = (duration: IDuration) => {
    return selectedDurationValue.value === duration.value ? 'active' : '';
};

        // 显示开始时间选择器
const showStartTimePicker = () => {
    const now = new Date();
    const selectedDate = dateOptions.value[selectedDateIndex.value]?.date;
    const isToday = selectedDate && selectedDate.toDateString() === now.toDateString();

    if (isToday) {
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        const hourIndex = hoursList.value.indexOf(currentHour.toString().padStart(2, '0'));
        const minuteIndex = minutesList.value.indexOf(currentMinute.toString().padStart(2, '0'));
        pickerValue.value = [hourIndex !== -1 ? hourIndex : 0, minuteIndex !== -1 ? minuteIndex : 0];
        tempTime.value = `${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`;
    } else if (startTime.value) {
        const [hours, minutes] = startTime.value.split(':').map(Number);
        const hourIndex = hoursList.value.indexOf(hours.toString().padStart(2, '0'));
        const minuteIndex = minutesList.value.indexOf(minutes.toString().padStart(2, '0'));
        pickerValue.value = [hourIndex !== -1 ? hourIndex : 0, minuteIndex !== -1 ? minuteIndex : 0];
        tempTime.value = startTime.value;
    } else {
        pickerValue.value = [0, 0];
        tempTime.value = '00:00';
    }

    // 显示弹窗
    showTimePicker.value = true;
};

        // 时间选择器变化
const onTimePickerChange = (e: any) => {
            const values = e.detail.value;
    const hours = hoursList.value[values[0]];
    const minutes = minutesList.value[values[1]];
    tempTime.value = `${hours}:${minutes}`;
};

        // 取消时间选择
const cancelTimePicker = () => {
    showTimePicker.value = false;
};

        // 确认时间选择
const confirmTimePicker = () => {
    startTime.value = tempTime.value;
    showTimePicker.value = false;

            // 更新结束时间
    updateEndTime();
};

        // 更新结束时间
const updateEndTime = () => {
    const duration = parseInt(selectedDurationValue.value);
    const [hoursStr, minutesStr] = startTime.value.split(':');
    const startHour = parseInt(hoursStr);
    const startMinute = minutesStr;

            let endHour = startHour + duration;
            if (endHour >= 24) {
                endHour = endHour - 24;
        showNextDay.value = true;
            } else {
        showNextDay.value = false;
            }

    endTime.value = `${endHour.toString().padStart(2, '0')}:${startMinute}`;
};

// 获取当天时间线小时块的样式类
const getHourClass = (hour: number) => {
    // 根据当前时间和预订情况返回不同的状态类
    const reservedTime = reverseTime.value;
    // 获取界面上选择的日期
    const selectedDate = dateOptions.value[selectedDateIndex.value]?.date;
    if (!selectedDate) return 'available';

    const selectedFormattedDate = `${selectedDate.getFullYear()}-${(selectedDate.getMonth() + 1).toString().padStart(2, '0')}-${selectedDate.getDate().toString().padStart(2, '0')}`;

    // 检查是否在已预订时间范围内
    const isReserved = reservedTime.some(reservation => {
        return reservation.startDate === selectedFormattedDate && 
               hour >= reservation.startHour && 
               (reservation.endDate === selectedFormattedDate ? hour < reservation.endHour : true);
    });

    if (isReserved) {
        return 'unavailable';
    }

    // 如果选择的日期是今天，才检查当前时间
    const currentDate = new Date();
    const isToday = selectedDate.toDateString() === currentDate.toDateString();
    if (isToday) {
        const currentHour = currentDate.getHours();
        if (hour < currentHour) {
            return 'unavailable';
        }
    }

    if (startTime.value) {
        const [startHoursStr] = startTime.value.split(':');
        const startHour = parseInt(startHoursStr);
        const duration = parseInt(selectedDurationValue.value);
        const endHour = startHour + duration;
        if (hour >= startHour && (endHour <= 24 ? hour < endHour : true)) {
            return 'current';
        }
    }

    return 'available';
};

// 获取次日小时块的样式类
// 获取次日时间线小时块的样式类
const getNextDayHourClass = (hour: number) => {
    // 根据当前时间和预订情况返回不同的状态类
    const reservedTime = reverseTime.value;
    // 获取界面上选择的日期的次日
    const selectedDate = dateOptions.value[selectedDateIndex.value]?.date;
    if (!selectedDate) return 'available';

    const nextDate = new Date(selectedDate);
    nextDate.setDate(selectedDate.getDate() + 1);
    const nextFormattedDate = `${nextDate.getFullYear()}-${(nextDate.getMonth() + 1).toString().padStart(2, '0')}-${nextDate.getDate().toString().padStart(2, '0')}`;

    // 检查是否在已预订时间范围内
    const isReserved = reservedTime.some(reservation => {
        return reservation.endDate === nextFormattedDate && 
               hour < reservation.endHour && 
               (reservation.startDate === nextFormattedDate ? hour >= reservation.startHour : true);
    });

    if (isReserved) {
        return 'unavailable';
    }

    if (startTime.value && showNextDay.value) {
        const [startHoursStr] = startTime.value.split(':');
        const startHour = parseInt(startHoursStr);
        const duration = parseInt(selectedDurationValue.value);
        const endHour = startHour + duration;
        if (endHour > 24 && hour < (endHour - 24)) {
            return 'current';
        }
    }

    return 'available';
};

// 计算当前时间
const startHour = computed(() => parseInt(startTime.value.split(':')[0]));
const endHour = computed(() => {
    const duration = parseInt(selectedDurationValue.value);
    let end = startHour.value + duration;
    if (end >= 24) end -= 24;
    return end;
});

// 跳转到充值页面
const goToRecharge = () => {
            uni.navigateTo({
                url: '/pages/recharge/recharge'
            });
};

// 使用团购券
const useVoucher = () => {
            uni.showToast({
                title: '验券下单功能开发中',
                icon: 'none'
            });
};

// 提交预订订单
const submitReservation = async () => {
    try {
        // 表单验证
        if (!startTime.value) {
            uni.showToast({
                title: '请选择开始时间',
                icon: 'none'
            });
            return null;
        }

        // if (parseFloat(totalPrice.value) <= 0) {
        //     uni.showToast({
        //         title: '订单金额异常，请重新选择',
        //         icon: 'none'
        //     });
        //     return null;
        // }

        uni.showLoading({
            title: '提交中'
        });
        
        const reservationData = {
            room_id: roomId.value,
            date: formattedDate.value,
            start_time: startTime.value,
            end_time: endTime.value,
            duration: parseInt(selectedDurationValue.value),
            is_next_day: showNextDay.value ? 1 : 0,
            amount: parseFloat(totalPrice.value)
        };
        
        console.log('提交预订数据:', reservationData);
        
        const res = await request.post('/api/mobile/reservation/create', reservationData);
        console.log('预订创建响应:', res);
        
        if (res.code === 200) {
            // 创建订单成功，返回订单ID
            return res.data.order_id || res.data.id;
        } else {
            uni.showToast({
                title: res.message || '创建订单失败',
                icon: 'none',
                duration: 2000
            });
            return null;
        }
    } catch (error) {
        console.error('提交预订失败:', error);
        uni.showToast({
            title: error.message || '网络异常，请稍后重试',
            icon: 'none',
            duration: 2000
        });
        return null;
    } finally {
        uni.hideLoading();
    }
};

// 获取支付链接
const getPaymentUrl = async (orderId) => {
    try {
        uni.showLoading({
            title: '获取支付信息'
        });
        
        const res = await request.post(`/api/mobile/reservation/pay/${orderId}`);
        console.log('获取支付链接响应:', res);
        
        if (res.code === 200 && res.data && res.data.payment_url) {
            return res.data.payment_url;
        } else if (res.code === 200 && res.data && res.data.redirect_url) {
            return res.data.redirect_url;
        } else {
            uni.showToast({
                title: res.message || '获取支付链接失败',
                icon: 'none',
                duration: 2000
            });
            return null;
        }
    } catch (error) {
        console.error('获取支付链接失败:', error);
        uni.showToast({
            title: '获取支付信息失败',
            icon: 'none',
            duration: 2000
        });
        return null;
    } finally {
        uni.hideLoading();
    }
};

// 打开支付页面
const openPaymentPage = (paymentUrl) => {
    // 设置支付URL到本地存储，以便WebView页面获取
    uni.setStorageSync('PAYMENT_URL', paymentUrl);
    
    // 微信小程序环境，通过WebView页面处理
    // #ifdef MP-WEIXIN
    uni.navigateTo({
        url: `/pages/payment/webview?payUrl=${encodeURIComponent(paymentUrl)}`
    });
    return;
    // #endif
    
    // 其他环境，使用模拟支付流程
            uni.showModal({
        title: '跳转到支付',
        content: '请在浏览器中完成支付，支付完成后返回',
        showCancel: false,
        success: () => {
            // 模拟支付完成
            simulatePaymentComplete();
        }
    });
};

// 模拟支付完成（实际项目中应通过回调处理）
const simulatePaymentComplete = () => {
    uni.showLoading({
        title: '处理中'
    });
    
    // 延迟2秒模拟支付过程
    setTimeout(() => {
        uni.hideLoading();
                        uni.showToast({
                            title: '支付成功',
                            icon: 'success'
                        });
        
        // 支付成功后跳转到订单列表页面
                        setTimeout(() => {
            uni.navigateTo({
                url: '/pages/order/order'
                            });
                        }, 1500);
    }, 2000);
};

// 确认支付
const confirmPayment = async () => {
    // 表单验证
    if (!startTime.value) {
        uni.showToast({
            title: '请选择开始时间',
            icon: 'none'
        });
        return;
    }
    
    // 检查所选房间数据是否加载完成
    if (!roomData.value || !roomData.value.id) {
        uni.showToast({
            title: '房间信息加载中，请稍后再试',
            icon: 'none'
        });
        return;
    }
    if (!isTimeValid()) {
        uni.showToast({
            title: '选择的时间为不可用时间段，请重新选择',
            icon: 'none'
        });
        return;
    }
    uni.showModal({
        title: '订单信息',
        content: `抵用券减免: ¥ ${couponDeduction.value}\n需支付: ¥ ${totalPrice.value}\n`,
        confirmColor: '#7FB992',
        success: async (res) => {
            if (res.confirm) {
                try {
                    console.log('创建订单');
                    // 1. 创建预订订单
                    const orderId = await submitReservation();
                    
                    if (!orderId) return;
                    
                    // 保存当前订单ID
                    uni.setStorageSync('CURRENT_ORDER_ID', orderId);
                   
                    // 根据用户余额判断是否直接使用余额支付
                    // if (userBalance.value >= parseFloat(totalPrice.value) && parseFloat(totalPrice.value) > 0) {
                    //     // 显示余额支付选项
                    //     uni.showModal({
                    //         title: '支付方式',
                    //         content: `检测到您的余额充足，是否使用余额支付 ¥${totalPrice.value}？`,
                    //         confirmText: '余额支付',
                    //         cancelText: '其他方式',
                    //         confirmColor: '#7FB992',
                    //         success: (payRes) => {
                    //             if (payRes.confirm) {
                    //                 // 使用余额支付
                    //                 balancePayment(orderId);
                    //             } else {
                    //                 // 跳转到支付选择页面
                    //                 uni.navigateTo({
                    //                     url: `/pages/payment/payment?type=reservation&id=${orderId}`
                    //                 });
                    //             }
                    //         }
                    //     });
                    // } else {
                        // 直接跳转到支付选择页面
                        uni.navigateTo({
                            url: `/pages/payment/payment?type=reservation&id=${orderId}`
                        });
                    // }
                } catch (error) {
                    console.error('预约过程出错:', error);
                    uni.showToast({
                        title: '预约失败，请重试',
                        icon: 'none'
                    });
                }
            }
        }
    });
};
// 检查选择的时间是否有效
const isTimeValid = () => {
    const [startHoursStr, startMinutesStr] = startTime.value.split(':');
    const startHour = parseInt(startHoursStr);
    const startMinute = parseInt(startMinutesStr);
    const [endHoursStr, endMinutesStr] = endTime.value.split(':');
    const endHour = parseInt(endHoursStr);
    const endMinute = parseInt(endMinutesStr);
    const selectedDate = dateOptions.value[selectedDateIndex.value]?.date;
    const formattedDate = `${selectedDate.getFullYear()}-${(selectedDate.getMonth() + 1).toString().padStart(2, '0')}-${selectedDate.getDate().toString().padStart(2, '0')}`;
    // 获取当前时间
    const now = new Date();
    const currentDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const isSameDay = selectedDate.toDateString() === currentDate.toDateString();
    if (isSameDay) {
        const currentHour = now.getHours();
        const currentMinute = now.getMinutes();
        if (startHour < currentHour || (startHour === currentHour && startMinute < currentMinute)) {
            return false;
        }
    }
    // 检查当天时间是否可用
    let currentHour = startHour;
    let currentMinute = startMinute;
    while (true) {
        if (getHourClass(currentHour) === 'unavailable') {
            return false;
        }
        if (!showNextDay.value && (currentHour > endHour || (currentHour === endHour && currentMinute >= endMinute))) {
            break;
        }
        currentMinute += 1;
        if (currentMinute >= 60) {
            currentMinute = 0;
            currentHour += 1;
            if (currentHour >= 24) {
                break;
            }
        }
    }
    // 如果跨天，检查次日时间是否可用
    if (showNextDay.value) {
        currentHour = 0;
        currentMinute = 0;
        while (true) {
            if (getNextDayHourClass(currentHour) === 'unavailable') {
                return false;
            }
            if (currentHour > endHour || (currentHour === endHour && currentMinute >= endMinute)) {
                break;
            }
            currentMinute += 1;
            if (currentMinute >= 60) {
                currentMinute = 0;
                currentHour += 1;
            }
        }
    }
    return true;
};
// 使用余额支付
const balancePayment = async (orderId) => {
    try {
        uni.showLoading({
            title: '处理中'
        });
        
        const payData = {
            order_id: orderId,
            amount: parseFloat(totalPrice.value),
            businessType: 'reservation',
            paymentMethod: 'balance'
        };
        
        console.log('余额支付请求参数:', payData);
        
        const res = await request.post(`/api/mobile/payment/balance`, payData);
        
        if (res.code === 200) {
            uni.hideLoading();
            uni.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 2000
            });
            
            // 更新用户余额
            userBalance.value -= parseFloat(totalPrice.value);
            let couponId = uni.getStorageSync('coupon_id');
            //更新优惠券状态
            const res = await request.post(`/api/mobile/coupon/updateStatus`, { couponId });
            if(res.success){
                console.log('优惠券状态更新成功');
            }else{
                console.log('优惠券不存在');
            }
            // 支付成功后跳转到订单详情
            setTimeout(() => {
                uni.redirectTo({
                    url: `/pages/payment/result?status=success&orderId=${orderId}`
                });
            }, 1500);
        } else {
            uni.hideLoading();
            uni.showToast({
                title: res.message || '支付失败',
                icon: 'none',
                duration: 2000
            });
        }
    } catch (error) {
        uni.hideLoading();
        console.error('余额支付失败:', error);
        uni.showToast({
            title: '支付处理失败，请重试',
            icon: 'none',
            duration: 2000
        });
    }
};

// 页面加载时
onMounted(() => {
        // 获取当前时间作为默认开始时间
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
    startTime.value = `${hours}:${minutes}`;
    
    // 获取路由参数
    try {
        console.log('开始获取路由参数...');
        
        // 1. 首先尝试从本地存储获取（这是从首页跳转时保存的备份）
        try {
            const storedRoomId = uni.getStorageSync('RESERVE_ROOM_ID');
            if (storedRoomId) {
                console.log(`从本地存储获取到roomId: ${storedRoomId}`);
                roomId.value = storedRoomId;
                // 用完即删，避免影响下次使用
                uni.removeStorageSync('RESERVE_ROOM_ID');
            }
        } catch (storageError) {
            console.error('访问本地存储失败:', storageError);
        }
        
        // 2. 如果本地存储没有，再尝试从页面参数获取
        if (!roomId.value) {
            // 从页面参数获取
            const pages = getCurrentPages();
            console.log('当前页面栈:', pages);
            
            const currentPage = pages[pages.length - 1];
            console.log('当前页面:', currentPage);
            
            // 获取页面参数
            let pageParams = {};
            
            // 微信小程序环境下
            if (currentPage) {
                // 微信小程序页面参数通常在options或query中
                if (currentPage.options) {
                    pageParams = currentPage.options;
                    console.log('从options获取参数:', pageParams);
                } else if (currentPage.$page && currentPage.$page.options) {
                    pageParams = currentPage.$page.options;
                    console.log('从$page.options获取参数:', pageParams);
                } else if (currentPage.query) {
                    pageParams = currentPage.query;
                    console.log('从query获取参数:', pageParams);
                }
                
                // 尝试特殊的小程序对象结构
                if (!pageParams.roomId && !pageParams.room_id && currentPage.$vm) {
                    const mpContext = currentPage.$vm.$mp;
                    if (mpContext && mpContext.query) {
                        pageParams = mpContext.query;
                        console.log('从$vm.$mp.query获取参数:', pageParams);
                    }
                }
            }
            
            // 尝试获取roomId（支持不同格式）
            if (pageParams.roomId) {
                roomId.value = pageParams.roomId;
                console.log(`从参数获取到roomId: ${roomId.value}`);
            } else if (pageParams.room_id) {
                roomId.value = pageParams.room_id;
                console.log(`从参数获取到room_id: ${roomId.value}`);
            }
        }
        
        // 3. 如果还没有找到，尝试从URL中手动解析
        if (!roomId.value) {
            // 获取当前页面路由
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1]; 
            const pageRoute = currentPage?.route || '';
            
            console.log('当前页面路由:', pageRoute);
            
            // 获取完整URL（某些环境可用）
            if (currentPage && currentPage.fullPath) {
                const fullPath = currentPage.fullPath;
                console.log('完整路径:', fullPath);
                
                const queryIndex = fullPath.indexOf('?');
                if (queryIndex >= 0) {
                    const queryPart = fullPath.substring(queryIndex + 1);
                    const params = {};
                    
                    queryPart.split('&').forEach(item => {
                        const [key, value] = item.split('=');
                        if (key) params[key] = decodeURIComponent(value || '');
                    });
                    
                    console.log('解析的URL参数:', params);
                    if (params.roomId) roomId.value = params.roomId;
                    else if (params.room_id) roomId.value = params.room_id;
                }
            }
        }
        
        // 4. 尝试从全局对象获取（某些特殊情况下可用）
        if (!roomId.value && uni.getLaunchOptionsSync) {
            try {
                const launchOptions = uni.getLaunchOptionsSync();
                console.log('启动选项:', launchOptions);
                
                if (launchOptions && launchOptions.query) {
                    if (launchOptions.query.roomId) {
                        roomId.value = launchOptions.query.roomId;
                        console.log(`从启动选项获取roomId: ${roomId.value}`);
                    } else if (launchOptions.query.room_id) {
                        roomId.value = launchOptions.query.room_id;
                        console.log(`从启动选项获取room_id: ${roomId.value}`);
                    }
                }
            } catch (e) {
                console.error('获取启动选项失败:', e);
            }
        }
    } catch (error) {
        console.error('获取路由参数出错:', error);
    }
    
    console.log(`最终获取到的roomId: ${roomId.value}`);
    
    if (!roomId.value) {
        uni.showToast({
            title: '房间信息不存在',
            icon: 'none'
        });
        setTimeout(() => {
            uni.navigateBack();
        }, 1500);
        return;
    }
    
    // 初始化数据
    initDateOptions();
    initTimePickerData();
    
    // 获取房间信息
    fetchRoomDetail();
    
    // 获取用户信息
    fetchUserInfo();
    
    // 初始化结束时间
    updateEndTime();
});

// 获取页面通道
const getOpenerEventChannel = (): any => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    
    return {
        query: (currentPage && currentPage.$page && currentPage.$page.options) || {}
    };
};

// 获取当前页面
const getCurrentPages = (): any[] => {
    // @ts-ignore
    return uni.getCurrentPages ? uni.getCurrentPages() : [];
};
</script>

<style>
page {
    background-color: #f5f5f5;
}

.container {
    padding-bottom: 120rpx;
}

/* 房间信息 */
.room-info {
    background-color: #fff;
    padding: 30rpx;
    display: flex;
    margin-bottom: 20rpx;
}

.room-image-wrapper {
    width: 200rpx;
    height: 200rpx;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.room-image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
}

.room-details {
    flex: 1;
}

.room-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
}

.room-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
    margin-bottom: 16rpx;
}

.tag {
    padding: 4rpx 12rpx;
    background: rgba(127, 185, 146, 0.1);
    color: #7FB992;
    border-radius: 6rpx;
    font-size: 12px;
}

.room-notice {
    font-size: 24rpx;
    color: #666;
}

.notice-label {
    font-weight: bold;
    display: block;
    margin-bottom: 10rpx;
}

.notice-content {
    margin-bottom: 10rpx;
}

.notice-highlight {
    color: #7FB992;
    margin: 0 10rpx;
}

.notice-warning {
    display: block;
    margin-top: 10rpx;
}

/* 日期选择 */
.date-picker {
    background-color: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

.date-scroll {
    white-space: nowrap;
}

.date-item {
    display: inline-block;
    width: 150rpx;
    height: 150rpx;
    border-radius: 50%;
    text-align: center;
    margin-right: 20rpx;
    background-color: #f8f8f8;
    display: inline-flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.date-item.active {
    background-color: #7FB992;
    color: #fff;
}

.date-day {
    font-size: 28rpx;
    margin-bottom: 10rpx;
}

.date-label {
    font-size: 24rpx;
}

/* 时长选择 */
.duration-section {
    background-color: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

.section-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    display: block;
}

.duration-options {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.duration-row {
    display: flex;
    justify-content: space-between;
}

.duration-item {
    width: 31%;
    height: 120rpx;
    border: 1px solid #e0e0e0;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.duration-item.active {
    border-color: #7FB992;
    background-color: rgba(127, 185, 146, 0.1);
}

.duration-value {
    font-size: 28rpx;
    margin-bottom: 10rpx;
}

.duration-price {
    font-size: 24rpx;
    color: #FF0000;
}

/* 时间选择 */
.time-section {
    background-color: #fff;
    padding: 30rpx;
    margin-bottom: 20rpx;
}

.time-picker {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
}

.time-input {
    width: 200rpx;
    height: 80rpx;
    border: 1px solid #e0e0e0;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    position: relative;
}

.time-input.active {
    border-color: #7FB992;
    display: flex;
    align-items: center;
    justify-content: center;
}

.down-arrow {
    font-size: 20rpx;
    color: #7FB992;
    margin-left: 10rpx;
}

.time-separator {
    margin: 0 20rpx;
    font-size: 28rpx;
    color: #666;
}

/* 时间选择器弹窗 */
.picker-mask {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
    display: flex;
    align-items: flex-end;
}

.time-picker-popup {
    background-color: #fff;
    width: 100%;
    padding-bottom: 20rpx;
    border-radius: 20rpx 20rpx 0 0;
}

.picker-header {
    display: flex;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
}

.cancel-btn {
    color: #999;
    font-size: 32rpx;
}

.confirm-btn {
    color: #7FB992;
    font-size: 32rpx;
    font-weight: 500;
}

.time-picker-view {
    height: 500rpx;
    width: 100%;
}

.picker-item {
    line-height: 80rpx;
    text-align: center;
    font-size: 32rpx;
}

/* 时间段图例 */
.time-legend {
    display: flex;
    justify-content: space-around;
    margin-bottom: 30rpx;
}

.legend-item {
    display: flex;
    align-items: center;
}

.legend-color {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
}

.legend-color.current {
    background-color: #7FB992;
}

.legend-color.available {
    background-color: #E0E0E0;
}

.legend-color.unavailable {
    background-color: #FF6B6B;
}

.legend-text {
    font-size: 24rpx;
    color: #666;
}

/* 时间线 */
.timeline {
    margin-bottom: 30rpx;
}

.timeline-date {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
}

.timeline-hours {
    display: flex;
    height: 50rpx;
}

.hour-block {
    flex: 1;
    height: 100%;
    border-right: 1px solid #fff;
}

.hour-block:first-child {
    border-top-left-radius: 4rpx;
    border-bottom-left-radius: 4rpx;
}

.hour-block:last-child {
    border-top-right-radius: 4rpx;
    border-bottom-right-radius: 4rpx;
    border-right: none;
}

.hour-block.unavailable {
    background-color: #FF6B6B;
}

.hour-block.current {
    background-color: #7FB992;
}

.hour-block.available {
    background-color: #E0E0E0;
}

.hour-labels {
    display: flex;
    justify-content: space-between;
    font-size: 20rpx;
    color: #999;
    margin-top: 10rpx;
}

/* 订单信息 */
.order-info {
    background-color: #fff;
    padding: 30rpx;
}

.info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
}

.info-label {
    font-size: 28rpx;
    color: #333;
}

.info-value {
    font-size: 28rpx;
    color: #666;
}

.balance-section {
    display: flex;
    align-items: center;
}

.balance-value {
    font-size: 28rpx;
    color: #666;
    margin-right: 20rpx;
}

.recharge-btn {
    color: #FF0000;
    font-size: 24rpx;
    background-color: rgba(255, 0, 0, 0.1);
    padding: 4rpx 16rpx;
    border-radius: 4rpx;
}

/* 底部支付栏 */
.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.price-section {
    display: flex;
    align-items: baseline;
}

.price-label {
    font-size: 28rpx;
    color: #333;
    margin-right: 10rpx;
}

.price-value {
    font-size: 36rpx;
    color: #FF0000;
    font-weight: bold;
}

.action-btns {
    display: flex;
}

.voucher-btn {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 30rpx;
    border: 1px solid #7FB992;
    color: #7FB992;
    font-size: 28rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
}

.pay-btn {
    height: 80rpx;
    line-height: 80rpx;
    padding: 0 30rpx;
    background-color: #7FB992;
    color: #fff;
    font-size: 28rpx;
    border-radius: 40rpx;
}
</style>
